import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { getUserInfoApi,getUserMenuApi } from '@/service/index'
import type{ UserInfo,MenuList } from '@/service/type'


export const getUserInfo = createAsyncThunk('getUserInfo', async () => {
  const [userRes,menuRes] = await Promise.all([getUserInfoApi(),getUserMenuApi()]) 
  return {
    userInfo: userRes.data.data,
    menu: menuRes.data.data
  }
})

type State = {
  userInfo: UserInfo | null
  menuList: MenuList[]
}

const initialState: State = {
  userInfo: null,
  menuList: []
}


const userSlice = createSlice({
  name: 'user',
  initialState,
  reducers: {
    setUserInfo(state, action) {
      state.userInfo = action.payload
      console.log(state.userInfo)
    }
  },
  extraReducers(builder) {
    builder
      .addCase(getUserInfo.fulfilled, (state, action) => {
        state.userInfo = action.payload.userInfo
        state.menuList = action.payload.menu.list
      })
  },
})

export const { setUserInfo } = userSlice.actions
export default userSlice.reducer